<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>salvo</title>
  </head>
  {% include "user_list_frag.html" %}
  <script src="assets/js/tailwindcss.js" defer></script>
  <script src="assets/js/sweetalert2.js" defer></script>
  <script src="assets/js/alpinejs.js" defer></script>
  <script>
    function userForm() {
      return {
        users: [],
        total: 0,
        currentPage: 1,
        pageSize: 10,
        searchUsername: '',
        fetchData() {
          const params = new URLSearchParams({
            page: this.currentPage,
            size: this.pageSize,
            username: this.searchUsername
          });
          fetch(`/api/users?${params.toString()}`)
            .then((response) => {
              if (!response.ok) {
                throw new Error("Network response was not ok");
              }
              return response.json();
            })
            .then((data) => {
              this.users = data.data;
              this.total = data.total;
            })
            .catch((error) => {
              console.error(
                "There has been a problem with your fetch operation:",
                error
              );
            });
        },
        search() {
          this.currentPage = 1;
          this.fetchData();
        },
        prevPage() {
          if (this.currentPage > 1) {
            this.currentPage--;
            this.fetchData();
          }
        },
        nextPage() {
          if (this.currentPage < Math.ceil(this.total / this.pageSize)) {
            this.currentPage++;
            this.fetchData();
          }
        },
        addUser() {
          Swal.fire({
            title: "Add User",
            showCancelButton: true,
            confirmButtonText: "Yes",
            cancelButtonText: "Cancel",
            html: `
    <input id="swal-input1" class="swal2-input" placeholder="Username">
    <input id="swal-input2" class="swal2-input" placeholder="Password" type="password">
    `,
            preConfirm: () => {
              return fetch("/api/users", {
                method: "POST",
                headers: {
                  "Content-Type": "application/json",
                },
                body: JSON.stringify({
                  username: document.getElementById("swal-input1").value,
                  password: document.getElementById("swal-input2").value,
                }),
              })
                .then((response) => {
                  if (!response.ok) {
                    throw new Error(response.statusText);
                  }
                  this.fetchData();
                  return;
                })
                .catch((error) => {
                  Swal.showValidationMessage(`Request failed: ${error}`);
                });
            },
            allowOutsideClick: () => !Swal.isLoading(),
          });
        },
        updateUser(id, currentUsername) {
          Swal.fire({
            title: "Update",
            showCancelButton: true,
            confirmButtonText: "Yes",
            cancelButtonText: "Cancel",
            html: `
    <input id="swal-input1" class="swal2-input" placeholder="Username" value="${currentUsername}">
    <input id="swal-input2" class="swal2-input" placeholder="Password" type="password">
    `,
            preConfirm: () => {
              return fetch(`/api/users/${id}`, {
                method: "PUT",
                headers: {
                  "Content-Type": "application/json",
                },
                body: JSON.stringify({
                  username: document.getElementById("swal-input1").value,
                  password: document.getElementById("swal-input2").value,
                }),
              })
                .then((response) => {
                  if (!response.ok) {
                    throw new Error(response.statusText);
                  }
                  this.fetchData();
                  return;
                })
                .catch((error) => {
                  Swal.showValidationMessage(`Request failed: ${error}`);
                });
            },
            allowOutsideClick: () => !Swal.isLoading(),
          });
        },
        deleteUser(id) {
          Swal.fire({
            title: "Are you sure you want to delete?",
            text: "You won't be able to revert this!",
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: "Yes",
            cancelButtonText: "Cancel",
            preConfirm: () => {
              return fetch(`/api/users/${id}`, {
                method: "DELETE",
              })
                .then((response) => {
                  if (!response.ok) {
                    throw new Error(response.statusText);
                  }
                  this.fetchData();
                  return;
                })
                .catch((error) => {
                  Swal.showValidationMessage(`Request failed: ${error}`);
                });
            },
            allowOutsideClick: () => !Swal.isLoading(),
          });
        },
      };
    }
  </script>
</html>
